package com.holystone.orca.sys.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.holystone.orca.common.JSONMapper;
import com.holystone.orca.common.PageData;
import com.holystone.orca.sys.common.SystemConstant;
import com.holystone.orca.sys.mybatis.model.SysPrivilege;
import com.holystone.orca.sys.mybatis.model.SysPrivilegeRole;
import com.holystone.orca.sys.mybatis.model.SysRole;
import com.holystone.orca.sys.service.ISysPrivilegeRoleService;
import com.holystone.orca.sys.service.ISysPrivilegeService;
import com.holystone.orca.sys.service.ISysRoleService;
 
@Controller
@RequestMapping("/sys/role_management")
public class SysRoleController {

	private static Logger logger = Logger.getLogger(SysRoleController.class);
	
	
	private String baseUrl = "sys/role_management/";
	
	@Resource(name="RoleService")
	private ISysRoleService sysRoleService;
	
	@Resource(name="privilegeService")
	private ISysPrivilegeService sysPrivilegeService;
	
	@Resource(name="privilegeRoleService")
	private ISysPrivilegeRoleService sysPrivilegeRoleService;
	
	
    @RequestMapping("/menuRoleList")
    public ModelAndView initPersonList(){
    	ModelAndView model = new ModelAndView(baseUrl+"role_management");
        return model;
    }

    //分页，初始化角色页面
    @ResponseBody
    @RequestMapping("/pagingRoleList")
    public ModelMap pagingRoleList(String  iPageNo, String iPageSize,String roleName){
    	int pageindex = iPageNo!=null?Integer.parseInt(iPageNo):SystemConstant.default_pageNum;
        int pagesize = iPageSize!=null?Integer.parseInt(iPageSize):SystemConstant.default_pageSize;
        PageData pageData = new PageData();
        try{
        	
        	pageData = sysRoleService.pagingSysRole(pageindex, pagesize,"roleName",roleName);
        }catch(Exception e){
            logger.error(e,e);
        }
        return JSONMapper.createReturnMap(null, pageData, null);
    }
    
    
    //添加修改页面，分别绑定信息
    @RequestMapping(value="/initEditSysRole")
	public ModelAndView initEditSysRole(String roleId,String opera){
		logger.debug(">>>initEditSysPerson(String roleId,String opera)初始化角色添加修改页面");
		ModelAndView view = new ModelAndView(baseUrl+"add_role");
		SysRole role=null;
		if(opera!=null&&opera.equals("add")){//添加
			try {
			} catch (Exception e) {
				logger.error(e,e);
			}
		}else if(opera!=null&&opera.equals("edit")){//修改
			try {
				role=sysRoleService.selectRoleByRoleId(Integer.parseInt(roleId));
			} catch (Exception e) {
				logger.error(e,e);
			}
			view.addObject("role", role);
		}
		logger.debug("<<<initEditSysRole(SysRole sysRole)");
		return view;
	}
    
    //点击添加按钮
    @ResponseBody
    @RequestMapping("/insertSysRole")
    public ModelMap insertSysPerson(SysRole sysRole){
    	boolean flag=false;
    	Map<Object,String> map = new HashMap<Object,String>();
    	map.put("roleName", sysRole.getRoleName());
    	try {
    		if(sysRoleService.selectRole(map).size()==0){
    			flag=sysRoleService.insertRole(sysRole);
    		}else{
    			return JSONMapper.createReturnMap("角色名字重复！", null, flag);
    		}
		} catch (Exception e) {
			 logger.error(e,e);
		}
    	return JSONMapper.createReturnMap(null, null, flag);
    }
    
    
    //点击修改按钮
    @ResponseBody
    @RequestMapping("/updateSysRole")
    public ModelMap updateSysRole(SysRole sysRole){
    	boolean flag=false;
    	Map<Object,String> map = new HashMap<Object,String>();
    	map.put("roleName", sysRole.getRoleName());
    	map.put("roleId", sysRole.getRoleId()+"");
    	Map<Object,String> map1 = new HashMap<Object,String>();
    	map1.put("roleName", sysRole.getRoleName());
    	try {
    		if(sysRoleService.selectRole(map).size()==1){
    			flag=sysRoleService.updateRoleByRoleId(sysRole);
    			return JSONMapper.createReturnMap(null, null, flag);
    		}else if(sysRoleService.selectRole(map1).size()>=1){
    			return JSONMapper.createReturnMap("角色名字重复！", null, flag);
    		}else{
    			flag=sysRoleService.updateRoleByRoleId(sysRole);
    			return JSONMapper.createReturnMap(null, null, flag);
    		}

		} catch (Exception e) {
			 logger.error(e,e);
		}
    	return JSONMapper.createReturnMap(null, null, flag);
    }
    
    //初始化修改角色权限
    @ResponseBody
    @RequestMapping("/initEditSysRolePrivilege")
    public ModelAndView initEditSysRolePrivilege(ModelMap modelMap,int roleId){
    	modelMap.put("roleId", roleId);
    	ModelAndView model = new ModelAndView(baseUrl+"add_privilege");
        return model;
    }
    
    //初始化查看角色权限信息
    @ResponseBody
    @RequestMapping("/initLookSysRolePrivilege")
    public ModelAndView initLookSysRolePrivilege(ModelMap modelMap,int roleId){
    	modelMap.put("roleId", roleId);
    	ModelAndView model = new ModelAndView(baseUrl+"look_privilege");
        return model;
    }
    
    //初始化ztree，带选择框，初始其选择状态
    @ResponseBody
    @RequestMapping("/initPrivilege")
    public ModelMap initPrivilege(int roleId){
    	ModelMap modelMap = new ModelMap();
    	//所有权限节点
    	List<SysPrivilege> privilegeList=sysPrivilegeService.selectAllOpenPrivilege();
    	//用户的权限及每个权限节点对应的增删改
    	List<SysPrivilegeRole> list=sysPrivilegeRoleService.selectPrivilegeRoleByRoleId(roleId);
    	Map<Integer,String> actionPriMap = new HashMap<Integer,String>();
    	for(int i=0;i<list.size();i++){
    		actionPriMap.put(list.get(i).getPriId(), list.get(i).getActionPri()==null?"":list.get(i).getActionPri());
    	}
    	//当非“功能菜单”的url和“功能菜单”的url相同时，非“功能菜单”的ztree节点不拼接增删改
    	//非“功能菜单”包含“一级菜单”、“目录菜单”
    	//非“功能菜单”是否包含增删改
    	Set<String> priActon = new HashSet<String>();
    	Set<String> menuActon = new HashSet<String>();
    	
    	//获取不添加actionPri的privilege
    	for(SysPrivilege sp: privilegeList){
    		if(SystemConstant.PRI_TYPE_D.equals(sp.getPriType())){
    			priActon.add(sp.getProgCode());
    		}else if(SystemConstant.PRI_TYPE_C.equals(sp.getPriType())){
    			menuActon.add(sp.getProgCode());
    		}
    	}
    	//拼ztree
    	String nodes = "";
    	SysPrivilege spv = null;
    	for(int i=0;i<privilegeList.size();i++){
    		spv = privilegeList.get(i);
    		nodes +="{id:"+spv.getPriId()+", pId:"+spv.getPriPid()+", name:\""+spv.getPriName()
    				+"\" , open:true,checked:"+(actionPriMap.get(spv.getPriId())==null?false:true)+"},";
    		boolean checked = false;
    		
    		//“功能菜单”中包含url，则非“功能菜单”不拼接增删改
    		if(priActon.contains(spv.getProgCode())&&
    				(SystemConstant.PRI_TYPE_B.equals(spv.getPriType())||
    						SystemConstant.PRI_TYPE_C.equals(spv.getPriType()))){
    			continue;
    		}
    		if(menuActon.contains(spv.getProgCode())&&SystemConstant.PRI_TYPE_B.equals(spv.getPriType())){
     			continue;
     		}
    		 if(spv.getActionPri()!=null&&spv.getActionPri().length()>0){
    			 for(String action : spv.getActionPri().split(",")){
    				 switch (action){
    				 	case "1":
    				 		checked = actionPriMap.get(spv.getPriId())==null||!actionPriMap.get(spv.getPriId()).contains("1")?false:true;
    				 		nodes +="{id:'"+spv.getProgCode()+"#@#1',pId:"+spv.getPriId()+",name:\"新增\" ,open:true,checked:"+checked+"},";
    				 		break;
    				 	case "2":
    				 		checked = actionPriMap.get(spv.getPriId())==null||!actionPriMap.get(spv.getPriId()).contains("2")?false:true;
    				 		nodes +="{id:'"+spv.getProgCode()+"#@#2',pId:"+spv.getPriId()+",name:\"修改\" ,open:true,checked:"+checked+"},";
    				 		break;
    				 	case "3":
    				 		checked = actionPriMap.get(spv.getPriId())==null||!actionPriMap.get(spv.getPriId()).contains("3")?false:true;
    				 		nodes +="{id:'"+spv.getProgCode()+"#@#3',pId:"+spv.getPriId()+",name:\"删除\" ,open:true,checked:"+checked+"},";
    				 }
    			 }
    		 }
    	}
    	if(nodes != ""){
    		nodes = nodes.substring(0, nodes.length() - 1);
    	}
    	nodes ="["+nodes+"]";
    	modelMap.put("lstTree", nodes);
    	return modelMap;
    }
    
    //初始查看其权限，没分配的权限不显示，不带选择框
    @ResponseBody
    @RequestMapping("/initLookPrivilege")
    public ModelMap initLookPrivilege(int roleId){
    	ModelMap modelMap = new ModelMap();
    	List<SysPrivilegeRole> list=sysPrivilegeRoleService.selectPrivilegeRoleByRoleId(roleId);
    	List<Integer> priIdList=new ArrayList<Integer>();
    	//权限节点对应的操作权限
    	Map<Integer,String> actionPriMap = new HashMap<Integer,String>();
    	for(int i=0;i<list.size();i++){
    		priIdList.add(list.get(i).getPriId());
    		actionPriMap.put(list.get(i).getPriId(), list.get(i).getActionPri());
    	}
    	List<SysPrivilege> privilegeList=new ArrayList<SysPrivilege>();
		try {
			if(priIdList.size() !=0){
				privilegeList = sysPrivilegeService.selectPrivilegeByPriId(priIdList);
			}
		} catch (Exception e) {
			logger.error(e,e);
		}
		//当非“功能菜单”的url和“功能菜单”的url相同时，非“功能菜单”的ztree节点不拼接增删改
    	//非“功能菜单”包含“一级菜单”、“目录菜单”
    	//非“功能菜单”是否包含增删改
    	Set<String> priActon = new HashSet<String>();
    	Set<String> menuActon = new HashSet<String>();
    	
    	//获取功能菜单url
    	for(SysPrivilege sp: privilegeList){
    		if(SystemConstant.PRI_TYPE_D.equals(sp.getPriType())){
    			priActon.add(sp.getProgCode());
    		}else if(SystemConstant.PRI_TYPE_C.equals(sp.getPriType())){
    			menuActon.add(sp.getProgCode());
    		}
    	}
		
    	String nodes = "";
    	SysPrivilege spv = null;
    	for(int i=0;i<privilegeList.size();i++){
    		spv = privilegeList.get(i);
    		 nodes +="{id:"+spv.getPriId()+",pId:"+spv.getPriPid()+",name:\""+spv.getPriName()+"\" ,open:true},";
    		//“功能菜单”中包含url，则非“功能菜单”不拼接增删改
     		if(priActon.contains(spv.getProgCode())&&
     				(SystemConstant.PRI_TYPE_B.equals(spv.getPriType())||
     						SystemConstant.PRI_TYPE_C.equals(spv.getPriType()))){
     			continue;
     		}
     		if(menuActon.contains(spv.getProgCode())&&SystemConstant.PRI_TYPE_B.equals(spv.getPriType())){
     			continue;
     		}
    		 if(actionPriMap.get(spv.getPriId())!=null&&actionPriMap.get(spv.getPriId()).length()>0){
    			 for(String action : actionPriMap.get(spv.getPriId()).split(",")){
    				 switch (action){
    				 	case "1":
    				 		nodes +="{id:'"+spv.getPriId()+"-1',pId:"+spv.getPriId()+",name:\"新增\" ,open:true},";
    				 		break;
    				 	case "2":
    				 		nodes +="{id:'"+spv.getPriId()+"-2',pId:"+spv.getPriId()+",name:\"修改\" ,open:true},";
    				 		break;
    				 	case "3":
    				 		nodes +="{id:'"+spv.getPriId()+"-3',pId:"+spv.getPriId()+",name:\"删除\" ,open:true},";
    				 }
    			 }
    		 }
    		//lstTree.add(nodes);
    	}
    	if(nodes != ""){
    		nodes = nodes.substring(0, nodes.length() - 1);
    	}
    	nodes ="["+nodes+"]";
    	modelMap.put("lstTree", nodes);
    	return modelMap;
    }
    
    
    //为选定的角色修改添加权限
    @ResponseBody
    @RequestMapping("/addPrivilegeRole")
    public ModelMap addPrivilegeRole(int roleId,String checkedNodes){
    	boolean flag=false;
    	boolean flag1=false;
    	List<String> arrayCheckedNodes= new ArrayList<String>();
    	List<Integer> priIdList=new ArrayList<Integer>();
    	Map<String,String> actionPriMap = new HashMap<String,String>();
    	try {
    		for(String str: checkedNodes.split(",")){
    			if(str.contains("#@#")){
    				//没有url的菜单不做权限处理
    				if(str.startsWith("#@#")){
    					continue;
					}
    				//key为url value为权限值
    				String key = str.split("#@#")[0];
    				String value=str.split("#@#")[1];
    				if(actionPriMap.containsKey(key)){
    					actionPriMap.put(key, actionPriMap.get(key)+","+value);
    				}else{
    					actionPriMap.put(key, value);
    				}
    			}else{
    				arrayCheckedNodes.add(str);
    				priIdList.add(Integer.valueOf(str));
    			}
    		}
        	//权限节点对应的操作权限
    		List<SysPrivilege> privilegeList=new ArrayList<SysPrivilege>();
    		//权限节点对应的url
    		Map<String,String> priUrl = new HashMap<String,String>();
    		try {
    			if(priIdList.size() !=0){
    				privilegeList = sysPrivilegeService.selectPrivilegeByPriId(priIdList);
    				for(SysPrivilege sp : privilegeList){
    					priUrl.put(sp.getPriId()+"", sp.getProgCode());
    				}
    			}
    		} catch (Exception e) {
    			logger.error(e,e);
    		}
			flag=sysPrivilegeRoleService.delPrivilegeRoleByRoleId(roleId);
			if(arrayCheckedNodes.size()==0){
				return JSONMapper.createReturnMap(null, null, flag);
			}
			for(int i=0;i < arrayCheckedNodes.size();i++){
				SysPrivilegeRole sysPrivilegeRole=new SysPrivilegeRole();
				sysPrivilegeRole.setPriId(Integer.parseInt(arrayCheckedNodes.get(i)));
				sysPrivilegeRole.setRoleId(roleId);
				sysPrivilegeRole.setActionPri(actionPriMap.get(priUrl.get(arrayCheckedNodes.get(i)+"")));
				flag1=sysPrivilegeRoleService.addPrilegeRole(sysPrivilegeRole);
			}

		} catch (Exception e) {
			 logger.error(e,e);
		}
    	flag=(flag&&flag1);
    	return JSONMapper.createReturnMap(null, null, flag);
    }
    
    //删除角色信息，和其拥有的权限
    @ResponseBody
    @RequestMapping("/deleteRoleByRoleId")
    public ModelMap deleteRoleByRoleId(int roleId){
    	boolean flag=false;
    	try {
    		flag=sysPrivilegeRoleService.delPrivilegeRoleByRoleId(roleId) && 
    				sysRoleService.delRoleByRoleId(roleId);
    	} catch (Exception e) {
    		logger.error(e,e);
    	}
    	return JSONMapper.createReturnMap(null, null, flag);
    }
    
    
    //多项删除，删除选中的角色
    @ResponseBody
    @RequestMapping("/deleteSelectSysRole")
    public ModelMap deleteSelectSysRole(String checkedDel){
    	boolean flag=false;
    	checkedDel=checkedDel.substring(0, checkedDel.length() - 1);
    	String[] arry=null;
    	arry=checkedDel.split(",");
    	List<Integer> list=new ArrayList<Integer>();
    	for(int i=0;i<arry.length;i++){
    		list.add(Integer.parseInt(arry[i]));
    	}
    	try {
    		flag=(
    				sysRoleService.delSelectRole(list)&&
    				sysPrivilegeRoleService.delSelectPrilegeRole(list)
    				);
    	} catch (Exception e) {
    		logger.error(e,e);
    	}
    	return JSONMapper.createReturnMap(null, null, flag);
    }
    
}